<template>
  <div class="tab-container">
    <div class="tabs">
      <div
          v-for="(tab, index) in tabs"
          :key="tab.id"
          :class="['tab', { active: currentTab === index }]"
          @click="selectTab(index)"
      >
        {{ tab.title }}
        <button @click.stop="closeTab(index)">x</button>
      </div>
    </div>
    <div class="tab-content">
      <component v-if="currentTab !== null" :is="currentTabComponent" />
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';

export default {
  name: 'TabContainer',
  data() {
    return {
      currentTab: null,
    };
  },
  computed: {
    ...mapState(['tabs']),
    currentTabComponent() {
      return this.currentTab !== null ? this.tabs[this.currentTab].component : null;
    },
  },
  methods: {
    ...mapMutations(['addTab', 'removeTab']),
    selectTab(index) {
      this.currentTab = index;
    },
    closeTab(index) {
      this.removeTab(index);
      if (this.currentTab === index) {
        this.currentTab = this.tabs.length ? 0 : null;
      } else if (this.currentTab > index) {
        this.currentTab--;
      }
    },
  },
  created() {
    // 动态加载组件
    this.$store.commit('addTab', { id: 1, title: '组件1', component: () => import('@/components/Component1.vue') });
  },
};
</script>

<style>
.tab-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.tabs {
  display: flex;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
}
.tab {
  padding: 10px;
  cursor: pointer;
  position: relative;
}
.tab.active {
  background-color: #fff;
  border-bottom: 2px solid #42b983;
}
.tab button {
  position: absolute;
  top: 5px;
  right: 5px;
  background: none;
  border: none;
  cursor: pointer;
}
.tab-content {
  flex: 1;
  padding: 20px;
  background-color: #fff;
}
</style>